package hu.szyrt.bug.connections;

import hu.szyrt.bug.utils.Assets;
import hu.szyrt.bug.utils.Config;
import hu.szyrt.bug.utils.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;

import android.util.Log;

public class DownloadPolaroidConnection extends BaseConnection {
		
	private String imageName;
	private File   imageFile;
	
	
	public DownloadPolaroidConnection(String name) {
		super(Config.URL_BUG_POLAROIDS);		
		this.imageName = name;
		this.imageFile = Assets.getCacheFile(imageName);
	}
	
	
	
	@Override
	protected void parameterizedURL() {
		this.url += this.imageFile.getName(); 
	}
	
	@Override
	public void run() {
		if(Utils.isSDAvailable()){
			parameterizedURL();
			if(download()){
				postSuccess();
			}else{				
				postError();
			}
		}else{
			this.errorText = "External storage (SD-ard) not available!";
			postError();
		}
	}
	
	@Override
	protected boolean download() {
		try {			
			URL downloadURL = new URL(url);
			
			// TODO: remove
			Log.d("bug", downloadURL.toExternalForm());
			
			HttpURLConnection.setFollowRedirects(true);
			HttpURLConnection conn = (HttpURLConnection)downloadURL.openConnection();							   
							   conn.setRequestMethod("GET");	
							   conn.setConnectTimeout(Config.CONNECTION_TIMEOUT);
							   conn.setReadTimeout(Config.CONNECTION_TIMEOUT);
							   conn.connect();
			Log.d("bug", "result:   " + conn.getResponseCode());
			if(conn.getResponseCode() == 200){				
				InputStream is = conn.getInputStream();
				FileOutputStream fos = new FileOutputStream(imageFile);
				Utils.copyFile(is, fos);
				fos.close();
				is.close();
				conn.disconnect();
				return true;
			}else{
				errorText = conn.getResponseMessage();
				conn.disconnect();
				return false;
			}
		} catch (MalformedURLException e) {
			errorText = e.getMessage();
			e.printStackTrace();
			return false;
		} catch(SocketTimeoutException e){
			errorText = "Server not respond.";
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			errorText = e.getMessage();
			e.printStackTrace();
			return false;
		}
	}
	
	// Getters ---------------------------
	public String getImageName() {
		return imageName;
	}
	
	public File getImageFile() {
		return imageFile;
	}
	
}
